const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const cors = require("@koa/cors");
const { testConnection } = require("./utils/db");
const swagger = require("./routes/swagger");

const index = require("./routes/index");
const login = require("./routes/login");

// error handler
onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
app.use(logger());

// 静态文件要在swagger之前
app.use(require("koa-static")(__dirname + "/public"));

// CORS - 确保允许swagger-ui的请求
app.use(
  cors({
    origin: "*", // 允许所有来源访问
    credentials: true,
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization", "Accept"],
  })
);

// views
app.use(
  views(__dirname + "/views", {
    extension: "ejs",
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;

  // 获取北京时间并格式化为 YYYY-MM-DD HH:mm:ss
  const date = new Date(Date.now() + 8 * 60 * 60 * 1000);
  const beijingTime = date.toISOString().replace(/T/, " ").substring(0, 19);

  console.log(`[${beijingTime}] ${ctx.method} ${ctx.url} - ${ms}ms`);
});

// 测试数据库连接
testConnection();

// routes - swagger要放在最前面
app.use(swagger.routes(), swagger.allowedMethods());
app.use(index.routes(), index.allowedMethods());
app.use(login.routes(), login.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
